import os, sys
APPLICATION_INSTALL_DIR = os.environ.get('SIMPLEAUTH_INSTALL')
if not APPLICATION_INSTALL_DIR:
    raise EnvironmentError("Must Set SIMPLEAUTH_INSTALL in the environment!")
sys.path.append(os.path.join(APPLICATION_INSTALL_DIR, "lib%spython" % os.sep))
from simple_auth.envbuilder import EnvironmentBuilder, UnsupportedEnvError

from sqlalchemy import *


class User(object):
    """simple auth user object"""
    def __init__(self, **kwargs):
        self.name = kwargs.get('name')
        self.password = kwargs.get('password')

class Service(object):
    """simple auth service object"""
    def __init__(self, **kwargs):
        self.name = kwargs.get('name')
    

class Role(object):
    """simple auth service role"""
    def __init__(self, **kwargs):
        self.name = kwargs.get('name')


class Resource(object):
    """resource object for remote/alternate user sources"""
    def __init__(self, **kwargs):
        self.name = kwargs.get('name')


class ResourceUser(object):
    def __init__(self, **kwargs):
        self.name = kwargs.get('name')
        self.password = kwargs.get('password')


env = EnvironmentBuilder()

if env.simple_dbtype.lower() == "mysql":
    from simple_auth.mysql_tables import users, services, roles, roles_services, roles_users, resources, resource_users, resource_users_roles
elif env.simple_dbtype.lower() == "oracle":
    from simple_auth.oracle_tables import users, services, roles, roles_services, roles_users, resources, resource_users, resource_users_roles
else:
    raise UnsupportedEnvError("Unsupported environment config: dbtype %s" % env.simple_dbtype.lower())


Role.mapper = mapper(Role, roles)

User.mapper = mapper(User, users, properties=dict(
  roles = relation(Role, secondary=roles_users, lazy=True),
))

Service.mapper = mapper(Service, services, properties=dict(
  roles = relation(Role, secondary=roles_services, lazy=True),
))

Resource.mapper = mapper(Resource, resources)

ResourceUser.mapper = mapper(ResourceUser, resource_users, properties=dict(
    resource = relation(Resource, uselist=False),
    roles = relation(Role, secondary=resource_users_roles, lazy=True),
))
